{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:38.780187Z",
     "start_time": "2025-04-16T12:32:38.773185Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "\n",
    "# 定义矩阵A\n",
    "A = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64)\n",
    "A\n"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 2., 3.],\n",
       "       [4., 5., 6.]])"
      ]
     },
     "execution_count": 195,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 195
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:38.810184Z",
     "start_time": "2025-04-16T12:32:38.792188Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算协方差矩阵\n",
    "AAT = A @ A.T\n",
    "AAT"
   ],
   "id": "b4a5e9e5e9f808ea",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[14., 32.],\n",
       "       [32., 77.]])"
      ]
     },
     "execution_count": 196,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 196
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:38.901184Z",
     "start_time": "2025-04-16T12:32:38.892186Z"
    }
   },
   "cell_type": "code",
   "source": [
    "ATA = A.T @ A\n",
    "ATA"
   ],
   "id": "ee66be33bc158999",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[17., 22., 27.],\n",
       "       [22., 29., 36.],\n",
       "       [27., 36., 45.]])"
      ]
     },
     "execution_count": 197,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 197
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:38.931185Z",
     "start_time": "2025-04-16T12:32:38.913185Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算AAT的特征值和特征向量\n",
    "eigenvalues_AAT, U = np.linalg.eig(AAT)\n",
    "eigenvalues_AAT"
   ],
   "id": "b4fdea79de669ace",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.59732747, 90.40267253])"
      ]
     },
     "execution_count": 198,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 198
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:38.992185Z",
     "start_time": "2025-04-16T12:32:38.972188Z"
    }
   },
   "cell_type": "code",
   "source": "U",
   "id": "f648f822ef06cc3e",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.92236578, -0.3863177 ],\n",
       "       [ 0.3863177 , -0.92236578]])"
      ]
     },
     "execution_count": 199,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 199
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.007185Z",
     "start_time": "2025-04-16T12:32:38.997189Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 按特征值降序排列\n",
    "sorted_idx_AAT = np.argsort(eigenvalues_AAT)[::-1]\n",
    "eigenvalues_AAT_sorted = eigenvalues_AAT[sorted_idx_AAT]\n",
    "U_sorted = U[:, sorted_idx_AAT]\n",
    "U_sorted"
   ],
   "id": "6bbe3cbd1fc89f7b",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.3863177 , -0.92236578],\n",
       "       [-0.92236578,  0.3863177 ]])"
      ]
     },
     "execution_count": 200,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 200
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.053188Z",
     "start_time": "2025-04-16T12:32:39.039191Z"
    }
   },
   "cell_type": "code",
   "source": "eigenvalues_AAT_sorted",
   "id": "bd445ea04c6667b3",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([90.40267253,  0.59732747])"
      ]
     },
     "execution_count": 201,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 201
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.098189Z",
     "start_time": "2025-04-16T12:32:39.076187Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 计算 ATA 的特征值和特征向量\n",
    "eigenvalues_ATA, V = np.linalg.eig(ATA)\n",
    "\n",
    "# 关键修复 1：强制转换为实数（因对称矩阵特征值必为实数）\n",
    "eigenvalues_ATA = np.real(eigenvalues_ATA)\n",
    "V = np.real(V)\n",
    "\n",
    "# 关键修复 2：按特征值降序排列并与 AAT 对齐\n",
    "sorted_idx_ATA = np.argsort(eigenvalues_ATA)[::-1]  # 降序索引\n",
    "eigenvalues_ATA = eigenvalues_ATA[sorted_idx_ATA]\n",
    "V = V[:, sorted_idx_ATA]  # 同步调整列顺序\n",
    "\n",
    "# 关键修复 3：符号一致性修正（仅处理非零奇异值）\n",
    "sigma = np.sqrt(eigenvalues_ATA)\n",
    "rank = 2  # 根据 A 的秩确定（或通过 np.linalg.matrix_rank(A) 动态计算）\n",
    "\n",
    "for i in range(rank):  # 仅遍历前 rank 个奇异值\n",
    "    v_col = V[:, i]\n",
    "    u_col = U_sorted[:, i]\n",
    "\n",
    "    Av = A @ v_col\n",
    "    expected = sigma[i] * u_col\n",
    "\n",
    "    # 使用更稳定的符号对齐方法\n",
    "    if not np.allclose(Av, expected, atol=1e-8):\n",
    "        V[:, i] *= -1\n",
    "\n",
    "V"
   ],
   "id": "a66dc376872b665f",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.42866713,  0.80596391,  0.40824829],\n",
       "       [-0.56630692,  0.11238241, -0.81649658],\n",
       "       [-0.7039467 , -0.58119908,  0.40824829]])"
      ]
     },
     "execution_count": 202,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 202
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.129184Z",
     "start_time": "2025-04-16T12:32:39.123190Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "75be12c62c7f30c8",
   "outputs": [],
   "execution_count": 202
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.160286Z",
     "start_time": "2025-04-16T12:32:39.141185Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 保留前6位有效数字\n",
    "for i in range(len(eigenvalues_ATA)):\n",
    "    eigenvalues_ATA[i] = round(eigenvalues_ATA[i], 6)\n",
    "\n",
    "eigenvalues_ATA"
   ],
   "id": "962186edfaa14cb",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([90.402673,  0.597327,  0.      ])"
      ]
     },
     "execution_count": 203,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 203
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.175813Z",
     "start_time": "2025-04-16T12:32:39.162814Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 确保 V 的转置（如果需要后续使用）\n",
    "V_T = V.T\n",
    "\n",
    "V_T"
   ],
   "id": "fb3df06f1437ac1c",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.42866713, -0.56630692, -0.7039467 ],\n",
       "       [ 0.80596391,  0.11238241, -0.58119908],\n",
       "       [ 0.40824829, -0.81649658,  0.40824829]])"
      ]
     },
     "execution_count": 204,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 204
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:51.636419Z",
     "start_time": "2025-04-16T12:32:51.617229Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 调整特征向量符号确保AV=σU\n",
    "sigma = np.sqrt(eigenvalues_AAT_sorted)\n",
    "for i in range(len(sigma)):\n",
    "    u_col = U[:, i]\n",
    "    v_col = V[:, i]\n",
    "    Av = A @ v_col\n",
    "    if np.dot(Av, u_col) < 0:\n",
    "        U[:, i] *= -1  # 仅需调整U或V中的一者即可\n",
    "        V[:, i] *= -1  # 若同时调整两者会导致符号反转两次\n",
    "print(\"sigma:\\n\", sigma)\n",
    "\n",
    "# 构造Σ矩阵\n",
    "Sigma = np.zeros((A.shape[0], A.shape[1]))\n",
    "np.fill_diagonal(Sigma, sigma)\n",
    "# 输出 Σ 矩阵以验证\n",
    "print(\"Σ:\\n\", Sigma)"
   ],
   "id": "fc09537a62e9f697",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sigma:\n",
      " [9.508032   0.77286964]\n",
      "Σ:\n",
      " [[9.508032   0.         0.        ]\n",
      " [0.         0.77286964 0.        ]]\n"
     ]
    }
   ],
   "execution_count": 210
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:52.066511Z",
     "start_time": "2025-04-16T12:32:52.049508Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "6d0a042c08564159",
   "outputs": [],
   "execution_count": 210
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:52.542608Z",
     "start_time": "2025-04-16T12:32:52.520608Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 验证分解结果\n",
    "reconstructed = (U_sorted @ Sigma) @ V_T\n",
    "reconstructed"
   ],
   "id": "fb34ee1c7b262bfb",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 2., 3.],\n",
       "       [4., 5., 6.]])"
      ]
     },
     "execution_count": 211,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 211
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.344814Z",
     "start_time": "2025-04-16T12:32:39.330815Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "print(\"U矩阵:\\n\", U_sorted)\n",
    "print(\"Σ矩阵:\\n\", Sigma)\n",
    "print(\"V.T矩阵:\\n\", V_T)\n",
    "print(\"\\n重构矩阵:\\n\", reconstructed)\n"
   ],
   "id": "7df1d02648828fdf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "U矩阵:\n",
      " [[-0.3863177  -0.92236578]\n",
      " [-0.92236578  0.3863177 ]]\n",
      "Σ矩阵:\n",
      " [[9.508032   0.         0.        ]\n",
      " [0.         0.77286964 0.        ]]\n",
      "V.T矩阵:\n",
      " [[-0.42866713 -0.56630692 -0.7039467 ]\n",
      " [ 0.80596391  0.11238241 -0.58119908]\n",
      " [ 0.40824829 -0.81649658  0.40824829]]\n",
      "\n",
      "重构矩阵:\n",
      " [[1. 2. 3.]\n",
      " [4. 5. 6.]]\n"
     ]
    }
   ],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.359811Z",
     "start_time": "2025-04-16T12:32:39.346810Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "90772634aa0d96fe",
   "outputs": [],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.374815Z",
     "start_time": "2025-04-16T12:32:39.362809Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "ff9232500e0f83b3",
   "outputs": [],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.404814Z",
     "start_time": "2025-04-16T12:32:39.385814Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "d11c7948e579c9c2",
   "outputs": [],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.419809Z",
     "start_time": "2025-04-16T12:32:39.407810Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "2932535f1de90274",
   "outputs": [],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.434824Z",
     "start_time": "2025-04-16T12:32:39.421808Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "6092ba6705261f45",
   "outputs": [],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.449834Z",
     "start_time": "2025-04-16T12:32:39.445814Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "a3fee86b169fcb6f",
   "outputs": [],
   "execution_count": 207
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T00:41:08.570912Z",
     "start_time": "2025-04-17T00:41:08.548680Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "\n",
    "# 定义矩阵 A\n",
    "A = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "\n",
    "# 使用 SVD 进行分解\n",
    "U, S, Vt = np.linalg.svd(A)\n",
    "\n",
    "# 动态生成对角矩阵 Σ\n",
    "Sigma = np.zeros((A.shape[0], A.shape[1]))  # 创建一个零矩阵，大小与 A 一致\n",
    "Sigma[:len(S), :len(S)] = np.diag(S)  # 将 S 的值填充到对角线上\n",
    "\n",
    "# 验证 SVD 的重构\n",
    "reconstructed_A = np.dot(np.dot(U, Sigma), Vt)\n",
    "\n",
    "# 输出结果\n",
    "print(\"U:\\n\", U)\n",
    "print(\"Σ:\\n\", Sigma)  # 更改命名，从 S_matrix 改为 Sigma\n",
    "print(\"Vt:\\n\", Vt)\n",
    "print(\"V:\\n\", Vt.T)\n",
    "print(\"Reconstructed A:\\n\", reconstructed_A)"
   ],
   "id": "cce04e8d9f40b6df",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "U:\n",
      " [[-0.3863177  -0.92236578]\n",
      " [-0.92236578  0.3863177 ]]\n",
      "Σ:\n",
      " [[9.508032   0.         0.        ]\n",
      " [0.         0.77286964 0.        ]]\n",
      "Vt:\n",
      " [[-0.42866713 -0.56630692 -0.7039467 ]\n",
      " [ 0.80596391  0.11238241 -0.58119908]\n",
      " [ 0.40824829 -0.81649658  0.40824829]]\n",
      "V:\n",
      " [[-0.42866713  0.80596391  0.40824829]\n",
      " [-0.56630692  0.11238241 -0.81649658]\n",
      " [-0.7039467  -0.58119908  0.40824829]]\n",
      "Reconstructed A:\n",
      " [[1. 2. 3.]\n",
      " [4. 5. 6.]]\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-16T12:32:39.479815Z",
     "start_time": "2025-04-16T12:32:39.468810Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "f84bddb17f576c69",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "U:\n",
      " [[-0.3863177  -0.92236578]\n",
      " [-0.92236578  0.3863177 ]]\n",
      "S:\n",
      " [[9.50803203 0.         0.        ]\n",
      " [0.         0.77286964 0.        ]]\n",
      "Vt:\n",
      " [[-0.42866713 -0.56630692 -0.7039467 ]\n",
      " [ 0.80596391  0.11238241 -0.58119908]\n",
      " [ 0.40824829 -0.81649658  0.40824829]]\n",
      "V:\n",
      " [[-0.42866713  0.80596391  0.40824829]\n",
      " [-0.56630692  0.11238241 -0.81649658]\n",
      " [-0.7039467  -0.58119908  0.40824829]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[1.        , 2.00000001, 3.00000001],\n",
       "       [4.00000001, 5.00000002, 6.00000002]])"
      ]
     },
     "execution_count": 209,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 209
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:13:52.823350Z",
     "start_time": "2025-04-17T11:13:52.809333Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "ac6fb0da8788661a",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:13:52.838349Z",
     "start_time": "2025-04-17T11:13:52.824352Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "146c31f32ad01b26",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:13:52.854350Z",
     "start_time": "2025-04-17T11:13:52.839351Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "885502468072cb1a",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:13:52.869333Z",
     "start_time": "2025-04-17T11:13:52.855335Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "fd0058b245e0e81b",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:22:10.017047Z",
     "start_time": "2025-04-17T11:22:10.003633Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 定义矩阵U\n",
    "import numpy as np\n",
    "\n",
    "U = np.array([[-0.39, -0.92], [-0.92, 0.39]], dtype=np.float64)\n",
    "U"
   ],
   "id": "4ecde9028cab3bfe",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.39, -0.92],\n",
       "       [-0.92,  0.39]])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:22:10.268482Z",
     "start_time": "2025-04-17T11:22:10.258481Z"
    }
   },
   "cell_type": "code",
   "source": [
    "sigma = np.array([[9.51, 0, 0], [0, 0.77, 0]], dtype=np.float64)\n",
    "sigma"
   ],
   "id": "4600e417d0a96418",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[9.51, 0.  , 0.  ],\n",
       "       [0.  , 0.77, 0.  ]])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:22:10.672119Z",
     "start_time": "2025-04-17T11:22:10.660130Z"
    }
   },
   "cell_type": "code",
   "source": [
    "V = np.array([\n",
    "    [-0.43, 0.81, 0.41],\n",
    "    [-0.57, 0.11, -0.82],\n",
    "    [-0.70, -0.58, 0.41]\n",
    "], dtype=np.float64)\n",
    "\n",
    "# V = np.array([\n",
    "#     [-0.42866713, 0.80596391, 0.40824829],\n",
    "#     [-0.56630692, 0.11238241, -0.81649658],\n",
    "#     [-0.7039467, -0.58119908, 0.40824829]\n",
    "# ], dtype=np.float64)\n",
    "V"
   ],
   "id": "15b591c03706dc01",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.43,  0.81,  0.41],\n",
       "       [-0.57,  0.11, -0.82],\n",
       "       [-0.7 , -0.58,  0.41]])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:22:10.940701Z",
     "start_time": "2025-04-17T11:22:10.924713Z"
    }
   },
   "cell_type": "code",
   "source": [
    "reconstructed_A = np.dot(np.dot(U, sigma), V.T)\n",
    "reconstructed_A"
   ],
   "id": "37b72720d4158d94",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.021023, 2.036149, 3.007102],\n",
       "       [4.005399, 5.020077, 5.950266]])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-17T11:22:11.327085Z",
     "start_time": "2025-04-17T11:22:11.315097Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "b946a8be944f6fe9",
   "outputs": [],
   "execution_count": 23
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "4c6ee2705ee67812"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
